class Solution {
    public int treeHeight(TreeNode root) {
        if(root==null) return 0;
        int leftHeight=treeHeight(root.left);
        int rightHeight=treeHeight(root.right);
        if(leftHeight>=0 && rightHeight>=0 && Math.abs(leftHeight-rightHeight)<=1) {
            return Math.max(leftHeight,rightHeight)+1;
        } else {
            return -1;
        }
    }
    public boolean isBalanced(TreeNode root) {
//        if(root==null) return true;
//        int leftRoot=treeHeight(root.left);
//        int rightRoot=treeHeight(root.right);
//        if(leftRoot==-1||rightRoot==-1) {
//            return false;
//        }
//        return Math.max(leftRoot,rightRoot)-Math.min(leftRoot,rightRoot)<=1 && isBalanced(root.left) &&
//                isBalanced(root.right);
        if(root==null) return true;
        return treeHeight(root)>=0;
    }
}